<template>
  <div class="simple-chart">
    <div class="simple-chart-inner" ref="main">
    </div>
  </div>
</template>
<script>

import * as echarts from 'echarts'
import { debounce } from 'throttle-debounce'
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'

export default {
  name: 'simple-chart',
  cnName: 'simple-chart',
  props: {
    options: Object
  },
  data() {
    return {}
  },
  created() {
    this.proxyResize = debounce(50, this.resize)
  },
  methods: {
    init() {
      this.chart = echarts.init(this.$refs.main);
      this.$nextTick(_ => {
        this.chart.setOption(this.options)
      })

      // 绑定echarts事件
      Object.entries(this.$listeners)
        .forEach(([name, handler]) => {
          this.chart.on(name, handler)
        })
      addResizeListener(this.$refs.main, this.proxyResize)
    },
    resize() {
      if (!this.chart) return
      this.chart.resize()
    },
    dispose() {
      if (!this.chart) return
      Object.entries(this.$listeners).forEach(([name, handler]) => {
        this.chart.off(name, handler)
      })
      this.chart.dispose()
      this.chart = null
      removeResizeListener(this.$el.main, this.proxyResize)
    }
  },
  watch: {
    options(){
      this.chart.setOption(this.options)
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.dispose()
  }
}
</script>
<style scoped lang="scss">
.simple-chart {
  position: relative;
  height: 100%;

  &-inner {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }

  &-tool {
    position: absolute;
    right: 0;
    top: -25px;
    cursor: pointer;
    z-index: 2;

    &:active {
      opacity: .8;
    }
  }

  &.full {
    top: 0;
    position: fixed !important;
    background: #031130;
    z-index: 9999;
    left: 0;
    right: 0;
    bottom: 0;

    .simple-chart-tool {
      top: 10px;
      right: 10px;
      color: #FFF;
    }
  }
}
</style>
